package com.binarycube.webserver;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;

import com.binarycube.webserver.config.ServerConfig;
import com.binarycube.webserver.session.ISessionManager;
import com.binarycube.webserver.session.Session;
import com.binarycube.webserver.wrappers.WrappedRequest;
import com.binarycube.webserver.wrappers.WrappedResponse;

public class LogoutHandler extends AbstractHandler {

	static Logger log = Logger.getLogger(LogoutHandler.class.getName());
	
	
	ServerConfig serverConfig;
	
	public LogoutHandler(ServerConfig config){
		serverConfig = config;
	}
	



	
	@Override
	public void handle(String target, final Request baseRequest,HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		
	    try {
        		    	  
	    	//Server wide response settings
	  	  
		     response.setCharacterEncoding("UTF-8");
		     //Wrap the request for processing
		     WrappedRequest wrappedRequest = new WrappedRequest(request);
		     WrappedResponse wrappedResponse = new WrappedResponse(response);
		     
		    
		     ISessionManager sm = serverConfig.getSessionManager();
		     Session session = sm.getSession(wrappedRequest);
		     if (session != null)  sm.endSession(wrappedResponse, session);
		     response.sendRedirect(request.getPathInfo());
		     response.flushBuffer();
             baseRequest.setHandled(true);
		     
        	
       		
        } catch (Exception e) {
        	log.error("Error handling page request: ", e);
        	response.sendError(HttpStatus.INTERNAL_SERVER_ERROR_500, "Oops, there has been a problem in the server:" + e.getLocalizedMessage());
        } 
		
		
	}
	

	

}

